<template>
    <div class="assignment-header">
        <button class="back-button" @click="$router.go(-1)"><img src="@/assets/svgs/left.svg" alt="Back" /></button>
        <span class="correct_header4" v-if="selectedHomework">{{ selectedHomework.homeworkName }}:</span>
        <span class="correct_header2">{{ userInfo?.nick_name }}</span>
        <span class="correct_header3" v-if="selectedHomework">截止提交时间：{{ selectedHomework.homeworkDeadline }}</span>
        <button type="success" class="assign_button" @click="assignHome">提交作业</button>
            </div>
    <div class="assignment-grading">
        <el-collapse v-model="activeNames">
            <el-collapse-item v-for="(item, index) in assignment" :key="item.questionId" :name="index">
                <template #title>
                    <h2 class="aler2">&nbsp;&nbsp;&nbsp;题目 {{ index + 1 }}&nbsp;&nbsp;&nbsp; ({{ item.scoreSet }}分)</h2>
                </template>
                <div class="answer_content">
                    <p class="smalltitle">问题内容:</p>
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{ item.question }}
        </div>
                <div class="correct_content3">
                    <span class="smalltitle"><span style="color: brown;font-weight: 900;">*&nbsp;</span>您的答案：</span>
                    <el-input class="grade_input" v-model="item.answer" placeholder="请输入答案" />
        </div>
            </el-collapse-item>
        </el-collapse>
    </div>
</template>



<script setup>
import { ref } from 'vue';
import { ElMessage, ElLoading } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { useCounterStore } from "@/stores/counter";
import { gethomeworkService, submitHomeworkService } from '@/api/homework';
import { informationService } from '@/api/personnal-information';
import { useUserIdStore } from '@/stores/userId'


//获取作业id
const route = useRoute(); // 获取当前路由对象
const router = useRouter();
const homeworkId = ref(null);
homeworkId.value = route.query.homeworkId; // 从路由参数中获取 homeworkId
console.log("获取到的作业Id:", homeworkId.value);

//获取学生Id
let userIdStore = useUserIdStore();
const userId = userIdStore.userId;
console.log("获取的学生id:", userId);

//从pinia获取课程ID
let store = useCounterStore();
const courseManageId = store.courseManageId;
console.log("获取的课程id:", courseManageId);


//查询作业列表

const selectedHomework = ref([]);
const assignment = ref([]);
const details = ref(false);
const fetchHomeworkList = async (courseManageId) => {
    const loading = ElLoading.service({
        lock: true,
        text: '加载中...',
        background: 'rgba(0, 0, 0, 0.7)'
    });
    try {
        const response = await gethomeworkService(courseManageId);

        const homeworkData = Array.isArray(response.data) ? response.data : [];
        // 遍历作业数据数组，找到与当前作业ID匹配的作业
        const matchingHomework = homeworkData.find(item => item.homeworkId === Number(homeworkId.value));
        if (matchingHomework) {
            selectedHomework.value = {
                homeworkId: matchingHomework.homeworkId,
                homeworkName: matchingHomework.homeworkName,
                homeworkDeadline: matchingHomework.deadline
            };
            console.log('获取的作业:', selectedHomework);
        } else {
            console.warn('未找到匹配的作业');
            selectedHomework.value = null; // 如果没有找到匹配的作业，清空 selectedHomework
            return; // 直接返回，不再执行后续代码
        }
        console.log("获取的作业详情:", matchingHomework);

        // 检查 matchingHomework 是否包含 question, scoreSet, questionId 属性
        if (Array.isArray(matchingHomework.question) && Array.isArray(matchingHomework.scoreSet) && Array.isArray(matchingHomework.questionId)) {
            assignment.value = matchingHomework.question.map((question, index) => ({
                question: question,
                scoreSet: matchingHomework.scoreSet[index],
                questionId: matchingHomework.questionId[index],
                answer: '' // 初始化答案为空字符串
            }));
            // 存储后端返回的所有数据
            details.value = true; // 显示作业详情模块
        } else {
            console.error('作业数据格式不正确');
            details.value = false; // 不显示作业详情模块
        }
        console.log("获取的作业数据:", assignment);
    } catch (error) {
        console.error('获取作业列表错误:', error);
    } finally {
        loading.close();
    }
};
fetchHomeworkList(courseManageId);

//导航栏部分获取学生姓名
const userInfo = ref(null);
const fetchUserInfo = async () => {
    try {
        const result = await informationService();
        const userData = result.data; // 假设后端返回的数据结构是 { data: SysUser }
        userInfo.value = {
            userId: userData.userId,
            avatarUrl: userData.avatar,
            user_name: userData.userName,
            nick_name: userData.nickName
        };
    } catch (error) {
        console.error('获取用户信息失败:', result.message);
    }
};
fetchUserInfo();



const activeNames = ref(); // 默认不展开个面板

//提交批改
// 定义 Answer 类型
class Answer {
  constructor(questionId, homeworkId, answer) {
    this.questionId = questionId;
    this.homeworkId = homeworkId;
    this.answer = answer;
  }
}
const assignHome = async () => {
  try {
    // 创建 Answer 对象数组
    const answers = assignment.value.map(item => new Answer(item.questionId, homeworkId.value, item.answer));
    console.log("提交的数据:", answers);
    const loading = ElLoading.service({
      lock: true,
      text: '提交中...',
      background: 'rgba(0, 0, 0, 0.7)'
    });


    // 发送 POST 请求
    const response = await submitHomeworkService(answers);
    if(response.code===0){
      ElMessage.success('提交成功');
      router.go(-1);
      loading.close();
    }else {
      ElMessage.error(`提交失败: ${response.message}`);
      loading.close();
    }
  } catch (error) {
    console.error('提交作业失败:', error);
    ElMessage.error(`提交失败: ${error.message}`);
    loading.close();
  }
};

</script>

<style scoped>
.assignment-header {
    display: flex;
    height: 7lvh;
    width: 99lvw;
    background-color: #13227A;
    color: white;
}

.back-button {
    background-color: transparent;
    border: none;
    color: white;
    cursor: pointer;
    font-size: 18px;
    font-weight: 700;
}

.back-button:hover {
    color: #d72d2d;
}

.correct_header1 {
    margin-left: 1%;
    margin-top: 1.2%;
}

.correct_header2 {
    margin-left: 1%;
    margin-top: 1.2%;
}

.correct_header3 {
    margin-left: 23%;
    margin-top: 1.2%;
}

.correct_header4 {
    margin-left: 35%;
    margin-top: 1.2%;
}

.assign_button {
    position: absolute;
    margin-top: 0.5%;
    margin-left: 88%;
    height: 5%;
    width: 10%;
    background-color: #1a3a8b;
    color: white;
    border: 1px solid #ffffff;
    cursor: pointer;
    border-radius: 5px;
}

.assign_button:hover {
    background-color: #98a2bb;
}

.assignment-grading {
    height: 89lvh;
    max-height: 89lvh;
    overflow-y: auto;
}

.correct_content {
    display: flex;
    flex-direction: column;
    height: 89lvh;
    width: 99lvw;
}

.correct_content1 {
    float: left;
    height: 30%;
    width: 100%;
    background-color: rgb(255, 255, 255);
}

.correct_title {
    margin-left: 4%;
    font-size: 22px;
    font-weight: 700;
    color: rgb(0, 0, 0);
}

.correct_question {
    margin-left: 2%;
    font-size: 18px;
    font-weight: 400;
    line-height: 10%;
    color: rgb(50, 47, 47);
}

.answer_content {
    margin-left: 2%;
    font-size: 14px;
    font-weight: 400;
    width: 95%;
    height: 12lvh;
    color: rgb(5, 5, 5);
    background-color: #f5f7f9;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.smalltitle {
    font-size: 16px;
    font-weight: 700;
    line-height: 5lvh;
    color: rgb(54, 54, 54);
}

.correct_content2 {
    float: left;
    height: 25%;
    margin-top: 1.5%;
    margin-left: 2%;
    width: 95%;
    background-color: #EFF6FF;
}

.correct_title2 {
    margin-left: 0.5%;
    font-size: 20px;
    font-weight: 700;
    line-height: 10%;
    color: rgb(0, 0, 0);
}

.correct_answer_cotent {
    font-size: 16px;
    color: #4B5563;
}

.correct_content3 {
    float: left;
    height: 13lvh;
    margin-top: 0.5%;
    margin-left: 2%;
    width: 94.5%;
    background-color: #EFF6FF;
    padding-top: 0.5%;
    padding-left: 0.5%;
}


.grade_input {
    margin-left: 0.3%;
    margin-bottom: 0.31%;
    width: 99%;
    height: 6lvh;
}


.aler2 {
    color: #333;
}

.aler3 {
    font-size: 16px;
    line-height: 1.6;
    margin-top: 10px;
    margin-bottom: 20px;
    color: #666;
    margin-left: 5%;
}

.correct_button {
  margin-left: 4%;
    margin-top: 1%;
  width: 92%;
    height: 10%;
}

.correct_button1 {
  margin-left: 25%;
  width: 12.5%;
    height: 80%;
  font-size: 24px;
  background-color: #13227A;
  color: white;
  border: 1px solid #ffffff;
  cursor: pointer;
  border-radius: 5px;
}

.correct_button1:hover {
  background-color: rgb(202, 124, 124);
}
</style>
